﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Media;

namespace Pg.BioMedics.SDR.Client.Multimedia
{
    /// <summary>
    /// Provides voice recording functionality
    /// </summary>
    internal class VoiceRecorder : IDisposable
    {
        #region Fields

        private string tempFile;
        private bool recording;

        #endregion

        #region Constructors

        internal VoiceRecorder()
        {
            this.tempFile = Path.Combine(Path.GetTempPath(), String.Format("{0}.wav", Guid.NewGuid().ToString()));
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets all recorder bytes
        /// </summary>
        public byte[] RecorderBytes
        {
            get
            {
                if (String.IsNullOrEmpty(this.tempFile))
                    return null;
                else if (!File.Exists(this.tempFile))
                    return null;

                return File.ReadAllBytes(this.tempFile);
            }
        }

        /// <summary>
        /// Determines if recording is in progress
        /// </summary>
        public bool Recording
        {
            get
            {
                return this.recording;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Begins recording
        /// </summary>
        internal void Record()
        {
            if (!this.recording)
            {
                MCIHelper.OpenWaveAudio();
                MCIHelper.Record();

                this.recording = true;
            }
        }

        /// <summary>
        /// Stops recording and saves result
        /// </summary>
        internal void Stop()
        {
            if (this.recording)
            {
                MCIHelper.Save(this.tempFile);
                MCIHelper.Close();

                this.recording = false;
            }
        }

        /// <summary>
        /// Stops recording and plays recorder sound
        /// </summary>
        internal void Play()
        {
            if (this.recording)
            {
                MCIHelper.Save(this.tempFile);
                MCIHelper.Close();

                this.recording = false;

                SoundPlayer player = new SoundPlayer(this.tempFile);
                player.Play();
            }
        }

        #endregion        
    
        #region IDisposable Members

        public void Dispose()
        {
            if (this.recording)
                Stop();

            if (!String.IsNullOrEmpty(this.tempFile))
            {
                if (File.Exists(this.tempFile))
                    File.Delete(this.tempFile);
                this.tempFile = null;
            }
        }

        #endregion
    }
}
